package com.yyk.yiliao.ui;


import android.Manifest;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.config.Constant;
import com.yyk.yiliao.config.MyApplication;
import com.yyk.yiliao.listener.DialogSureCancelListenter;
import com.yyk.yiliao.runtimepermissions.PermissionsManager;
import com.yyk.yiliao.runtimepermissions.PermissionsResultAction;
import com.yyk.yiliao.ui.counselling.activity.Five_Activity;
import com.yyk.yiliao.ui.find.fragment.Find_Fragment;
import com.yyk.yiliao.ui.home.fragment.Home_Fragment;
import com.yyk.yiliao.ui.login.activity.LogIn_Activity;
import com.yyk.yiliao.ui.message.ConversationListActivity;
import com.yyk.yiliao.ui.mine.fragment.Mine_Fragment;
import com.yyk.yiliao.ui.shop.fragment.ShoppingMall_Fragment;
import com.yyk.yiliao.util.DialogUtil;
import com.yyk.yiliao.util.MobileInfoUtils;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.dt.LocationUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Main_Activity extends BaseActivity {


    @BindView(R.id.mMain_content)//Fragment
            FrameLayout mMainContent;
    @BindView(R.id.mMain_rb_iv)
    ImageView mMainRbIv;
    @BindView(R.id.mMain_rb_tv)
    TextView mMainRbTv;
    @BindView(R.id.mMain_rb)
    LinearLayout mMainRb;
    @BindView(R.id.mMain_rb_iv2)
    ImageView mMainRbIv2;
    @BindView(R.id.mMain_rb_tv2)
    TextView mMainRbTv2;
    @BindView(R.id.mMain_rb2)
    LinearLayout mMainRb2;
    @BindView(R.id.mMain_rb_iv3)
    ImageView mMainRbIv3;
    @BindView(R.id.mMain_rb_tv3)
    TextView mMainRbTv3;
    @BindView(R.id.mMain_rb3)
    LinearLayout mMainRb3;
    @BindView(R.id.mMain_rb_iv4)
    ImageView mMainRbIv4;
    @BindView(R.id.mMain_rb_tv4)
    TextView mMainRbTv4;
    @BindView(R.id.mMain_rb4)
    LinearLayout mMainRb4;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.nihao)
    View nihao;
    @BindView(R.id.img_protruding)
    ImageView imgProtruding;
    @BindView(R.id.iv_yuandian2) //我的圆点
            ImageView ivYudian2;


    private int uid; //账号ID


    private Home_Fragment home_fragment;
    private ShoppingMall_Fragment shoppingMall_fragment;
    private Find_Fragment find_fragment;
    private Mine_Fragment mine_fragment = new Mine_Fragment();

    private Fragment[] mFragments;
    private int mIndex = 0;

    //用户登录到另一个设备
    public boolean isConflict = false;
    //删除用户帐户
    private boolean isCurrentAccountRemoved = false;
    private boolean jumpStart = false;
    private boolean quanxianStart = false;

    /**
     * 初始化下面的fragment
     */
    private void initFragment() {
        //首页
        home_fragment = new Home_Fragment();
        //商城
        shoppingMall_fragment = new ShoppingMall_Fragment();
        //发现
        find_fragment = new Find_Fragment();
        //个人中心
        mine_fragment = new Mine_Fragment();
        //添加到数组
        mFragments = new Fragment[]{home_fragment, shoppingMall_fragment, find_fragment, mine_fragment};

        //开启事务
        FragmentTransaction ft =
                getSupportFragmentManager().beginTransaction();

        //添加首页
        ft.add(R.id.mMain_content, home_fragment).commit();

        //默认设置为第0个
        setIndexSelected(0);


    }

    /**
     * 设置点击某个fragment
     *
     * @param index
     */
    private void setIndexSelected(int index) {

        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();


        //隐藏
        ft.hide(mFragments[mIndex]);
        //判断是否添加
        if (!mFragments[index].isAdded()) {
            ft.add(R.id.mMain_content, mFragments[index]).show(mFragments[index]);
        } else {
            ft.show(mFragments[index]);
        }
        ft.commit();
        //再次赋值
        mIndex = index;

    }


    /**
     * 清楚q切换我的界面底部颜色
     */
    private void cleanColorBottom() {
        mMainRbTv.setTextColor(getResources().getColor(R.color.gray_93));
        mMainRbIv.setImageResource(R.mipmap.icon_dbsy_wdj);

        mMainRbTv2.setTextColor(getResources().getColor(R.color.gray_93));
        mMainRbIv2.setImageResource(R.mipmap.icon_dbsc_wdj);

        mMainRbTv3.setTextColor(getResources().getColor(R.color.gray_93));
        mMainRbIv3.setImageResource(R.mipmap.icon_dbfx_wdj);

        mMainRbTv4.setTextColor(getResources().getColor(R.color.gray_93));
        mMainRbIv4.setImageResource(R.mipmap.icon_dbwd_wdj);
    }

    @OnClick({R.id.img_protruding, R.id.mMain_rb, R.id.mMain_rb2, R.id.mMain_rb3, R.id.mMain_rb4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_protruding:
//                //单独找到人聊天
//                Intent intent = new Intent();
//                intent.putExtra(EaseConstant.EXTRA_USER_ID, "doc_155");
////                                    Chat 单人聊天
//                intent.putExtra(EaseConstant.EXTRA_CHAT_TYPE, EMMessage.ChatType.Chat);
//                startAct(intent, SendAMessageActivity.class, null);//参数为要添加的好友的username和添加理由
//                //添加好友
//                try {
//                    EMClient.getInstance().contactManager().addContact("doc_155", "爱你摸摸大");
//                } catch (HyphenateException e) {
//                    e.printStackTrace();
//                }
                //                    <!--Android 底部弹出Activity - 梁超杰 - CSDN博客  https://blog.csdn.net/losingcarryjie/article/details/79452279-->
                startAct(Five_Activity.class);
                overridePendingTransition(R.anim.shortcut_in, R.anim.shortcut_jingzhi);
                break;
            case R.id.mMain_rb:
                setIndexSelected(0);
                cleanColorBottom();
                mMainRbTv.setTextColor(getResources().getColor(R.color.blue_14));
                mMainRbIv.setImageResource(R.mipmap.icon_dbsy);

                break;
            case R.id.mMain_rb2:
                setIndexSelected(1);
                cleanColorBottom();
                mMainRbTv2.setTextColor(getResources().getColor(R.color.blue_14));
                mMainRbIv2.setImageResource(R.mipmap.icon_dbsc);
                break;
            case R.id.mMain_rb3:
                setIndexSelected(2);
                cleanColorBottom();
                mMainRbTv3.setTextColor(getResources().getColor(R.color.blue_14));
                mMainRbIv3.setImageResource(R.mipmap.icon_dbfx);
                break;
            case R.id.mMain_rb4:
                uid = Hawk.get("uid", 0);
                Logger.i("账号id==" + uid);
                if (uid == 0) {
                    startAct(LogIn_Activity.class);
                    //TODO 不做任何操作
                } else {
                    cleanColorBottom();
                    setIndexSelected(3);
                    mMainRbTv4.setTextColor(getResources().getColor(R.color.blue_14));
                    mMainRbIv4.setImageResource(R.mipmap.icon_dbwd);
                }
                break;
        }
    }

    /**
     * 标记是否退出系统
     */
    private static final int WHAT_BACK = 1;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == WHAT_BACK) {
                isBack = false;
//                Hawk.delete("locationTv");

            }
        }
    };

    /**
     * 标记back键是否起作用
     */
    private boolean isBack = false;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        /**
         * back键起作用依赖系统，因此我们只能让他在两秒之后再按back键恢复到第一次按back键的状态
         * 能执行 super.onKeyUp(keyCode, event);的时候back键起作用
         */
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (!isBack) {
                ToastUtil.showShort(mActivity, "再按一次退出程序");
//                Toast.makeText(Main_Activity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                handler.sendEmptyMessageDelayed(WHAT_BACK, 2000);
                isBack = true;
                return true;
            }
        }
        return super.onKeyUp(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        LocationUtils.getInstance(this).removeLocationUpdatesListener();

        /**
         * 在不需要的时候移除 监听
         */
        EMClient.getInstance().chatManager().removeMessageListener(msgListener);
        super.onDestroy();

    }

    @Override
    protected void onStart() {
        super.onStart();


    }


    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        initToolbar();
        initFragment();
        isStartMessageTz();
        initLocation();
        requestPermissions();
//        jumpStartInterface();


    }


    private void initToolbar() {
        hidetoolBar();
    }

    @Override
    public void initData() {
        //第一次安装做判断使用
        Hawk.put("MAIN_ACTIVITY", "2");
    }


    //----------以下动态获取权限---------
    @Override
    protected void onResume() {
        super.onResume();
//        if (isNeedCheck) {
//            checkPermissions(needPermissions);
//        }
        if (!isConflict && !isCurrentAccountRemoved) {
            updateUnreadLabel();
        }
        initGaode();
        //监听消息
        EMClient.getInstance().chatManager().addMessageListener(msgListener);
        initLocation();
    }


    /**
     * 2.收到消息监听
     */
    EMMessageListener msgListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            refreshUIWithMessage();

        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            //收到透传消息
        }

        @Override
        public void onMessageRead(List<EMMessage> messages) {
            //收到已读回执
        }

        @Override
        public void onMessageDelivered(List<EMMessage> message) {
            //收到已送达回执
        }

        @Override
        public void onMessageRecalled(List<EMMessage> messages) {
            //消息被撤回
            refreshUIWithMessage();
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
            //消息状态变动

        }
    };


    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                // refresh unread count
                updateUnreadLabel();
                if (mine_fragment.flagOnclick) {
                    mine_fragment.updateUnreadLabel();

                }
                if (ConversationListActivity.flagMessage) {
                    ConversationListActivity.intance.updateUnreadLabel();
                    ConversationListActivity.intance.upateListNumber();
                }
            }
        });
    }

    /**
     * 1.更新环信发送的消息数量
     */

    public void updateUnreadLabel() {
        final int count = getUnreadMsgCountTotal();
        if (count > 0) {
            ivYudian2.setVisibility(View.VISIBLE);
        } else {
            ivYudian2.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 获取消息数量
     *
     * @return
     */
    public int getUnreadMsgCountTotal() {
        return EMClient.getInstance().chatManager().getUnreadMsgsCount();
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra(Constant.ACCOUNT_CONFLICT, false)) {
            // 显示帐号在其他设备登录
            new Thread(new Runnable() {
                @Override
                public void run() {
                    EMClient.getInstance().logout(false);
                }
            }).start();
            DialogUtil.getIntanse().showReturnTips(mActivity, "", "您的账号在其他地方登陆", "确认", "", new DialogSureCancelListenter() {
                @Override
                public void onSureListenter() {

//                    ivYudian2.setVisibility(View.INVISIBLE);
                    MyApplication.getInstance().destroyActivity();
                }

                @Override
                public void onCancelListenter() {

                }
            }, true);
        }
    }

    /**
     * Jump Start Interface
     * 提示是否跳转设置自启动界面
     */
    private void jumpStartInterface() {
        jumpStart = Hawk.get("JumpStart");
        if (jumpStart) {
            try {
                androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
                builder.setMessage("请设置自启动管理功能");
                builder.setPositiveButton("立即设置",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                MobileInfoUtils.jumpStartInterface(mActivity);
                            }
                        });
                builder.setNegativeButton("暂时不设置",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                builder.setCancelable(false);
                builder.create().show();
            } catch (Exception e) {
            }
            Hawk.put("JumpStart", false);
        }
    }

    /**
     * 是否开启消息通知
     */
    private void isStartMessageTz() {
        //判断该app是否打开了通知，如果没有的话就打开手机设置页面
        if (!isNotificationEnabled()) {
            quanxianStart = Hawk.get("QuanxianStart");
            if (quanxianStart) {
                try {
                    androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
                    builder.setMessage("请开启消息通知");
                    builder.setPositiveButton("立即设置",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    gotoSet();
                                }
                            });
                    builder.setNegativeButton("暂时不设置",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    builder.setCancelable(false);
                    builder.create().show();
                } catch (Exception e) {
                }
                Hawk.put("QuanxianStart", false);
            }

        } else {
            //当前app允许消息通知
        }
    }

    private boolean isNotificationEnabled() {

        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

        AppOpsManager mAppOps = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = getApplicationInfo();
        String pkg = getApplicationContext().getPackageName();
        int uid = appInfo.uid;

        Class appOpsClass = null;
     /* Context.APP_OPS_MANAGER */
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }


    private void gotoSet() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= 26) {
            // android 8.0引导
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());
        } else if (Build.VERSION.SDK_INT >= 21) {
            // android 5.0-7.0
            intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
            intent.putExtra("app_package", getPackageName());
            intent.putExtra("app_uid", getApplicationInfo().uid);
        } else {
            // 其他
            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            intent.setData(Uri.fromParts("package", getPackageName(), null));
        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

    }


    /**
     * 原生定位
     */
    private void initLocation() {
        Location location = LocationUtils.getInstance(getApplicationContext()).showLocation();
        if (location != null) {
            String address = "纬度：" + location.getLatitude() + "精度：" + location.getLongitude();
            Logger.d("FLY.LocationUtils", address);
            String latitude = String.valueOf(location.getLatitude());
            String longitde = String.valueOf(location.getLongitude());
//            Hawk.put("经度", latitude);
//            Hawk.put("纬度", longitde);

        }
    }
    /**
     * Android 高德地图的定位功能，以及动态开启权限 - CSDN博客  https://blog.csdn.net/Dr_abandon/article/details/77946585?locationNum=6&fps=1
     */
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;
    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new MyAMapLocationListener();
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;


    /**
     * 初始化高德地图
     */
    private void initGaode() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //获取一次定位结果：
        //该方法默认为false。
        mLocationOption.setOnceLocation(false);
        /**
         * 设置是否优先返回GPS定位结果，如果30秒内GPS没有返回定位结果则进行网络定位
         * 注意：只有在高精度模式下的单次定位有效，其他方式无效
         */
//        mLocationOption.setGpsFirst(true);
//        // 设置发送定位请求的时间间隔,最小值为1000，如果小于1000，按照1000算
//        mLocationOption.setInterval(5000);
        //获取最近3s内精度最高的一次定位结果：
        //设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
        mLocationOption.setOnceLocationLatest(true);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();

    }

    /**
     * 高德地图返回信息
     */
    private class MyAMapLocationListener implements AMapLocationListener {

        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    //
                    //                        Log.e("进入", "回调" + "=========================================================================");
                    //                        if (aMapLocation != null) {
                    //                            if (aMapLocation.getErrorCode() == 0) {
                    //                                //可在其中解析amapLocation获取相应内容。
                    //                                Log.e("进入", "回调返回" + "aMapLocation != null=========================================================================");
                    //                                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                    //                                aMapLocation.getLatitude();//获取纬度
                    //                                aMapLocation.getLongitude();//获取经度
                    //                                aMapLocation.getAccuracy();//获取精度信息
                    //                                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                    //                                aMapLocation.getCountry();//国家信息
                    //                                aMapLocation.getProvince();//省信息
                    //                                aMapLocation.getCity();//城市信息
                    //                                aMapLocation.getDistrict();//城区信息
                    //                                aMapLocation.getStreet();//街道信息
                    //                                aMapLocation.getStreetNum();//街道门牌号信息
                    //                                aMapLocation.getCityCode();//城市编码
                    //                                aMapLocation.getAdCode();//地区编码
                    //                                aMapLocation.getAoiName();//获取当前定位点的AOI信息
                    //                                aMapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                    //                                aMapLocation.getFloor();//获取当前室内定位的楼层
                    //                                //   aMapLocation.getGpsStatus();//获取GPS的当前状态
                    //                                //获取定位时间
                    //                                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    //                                Date date = new Date(aMapLocation.getTime());
                    //                                df.format(date);
                    //                                tv.setText(aMapLocation.getAddress());
                    //
                    //                                String s = aMapLocation.getAddress();
                    //                                Log.e("定位成功，", "地址" + aMapLocation.getAddress());
                    ////                                if (!TextUtils.isEmpty(s)) {
                    ////                                    stopLocation();
                    ////                                }
                    //
                    Log.e("位置：", aMapLocation.getAddress());
                    String poiName = aMapLocation.getProvince();

                    String replace = poiName.replace("市", "").replace("省", "");
                    Log.e("位置：", replace);
                    Hawk.put("poiName", replace);

                    Hawk.put("经度", String.valueOf(aMapLocation.getLongitude()) + "");    //获取经度
                    Hawk.put("纬度", String.valueOf(aMapLocation.getLatitude()) + "");  //获取纬度
                    Logger.e("精度纬度" + aMapLocation.getLongitude() + "，" + aMapLocation.getLatitude());

                } else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                    Hawk.put("poiName", "城市");
                }
            }
        }
    }

    /**
     * 检查权限
     *
     * @param
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        //获取权限列表
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            //list.toarray将集合转化为数组
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        //for (循环变量类型 循环变量名称 : 要被遍历的对象)
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    this, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    /**
     * 群贤
     */
    @TargetApi(23)
    private void requestPermissions() {

        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(mActivity, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//                Toast.makeText(mActivity, "已授予所有权限 _All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
//                Toast.makeText(mActivity, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(grantResults)) {      //没有授权
                showMissingPermissionDialog();              //显示提示信息
                isNeedCheck = false;
            }
        }
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }

    /**
     * 权限没成功
     */
//    public static final int ACCESS_COARSE_LOCATION = 1;
//    public static final int ACCESS_FINE_LOCATION = 2;
//    public static final int WRITE_EXTERNAL_STORAGE = 3;
//    private static final int READ_EXTERNAL_STORAGE = 4;
//    private static final int READ_PHONE_STATE = 5;
//    private static final int CAMERA = 6;
//    private static final int CAPTURE_AUDIO_OUTPUT = 6;
//
//
//    protected String[] needPermissions = {
//            Manifest.permission.ACCESS_COARSE_LOCATION,
//            Manifest.permission.ACCESS_FINE_LOCATION,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.CAMERA,
//            Manifest.permission.CAPTURE_AUDIO_OUTPUT
//
//    };
//    protected int[] needPermissionsNumber = {
//            ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION, WRITE_EXTERNAL_STORAGE, READ_EXTERNAL_STORAGE, READ_PHONE_STATE,CAMERA,CAPTURE_AUDIO_OUTPUT
//
//    };

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
//            grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
//        Permissions4M.onRequestPermissionsResult(Main_Activity.this, requestCode, grantResults);
//    }
//
//    public void setQ() {
//        new Handler().post(new Runnable() {
//            @Override
//            public void run() {
//                Permissions4M.get(Main_Activity.this)
//                        .requestForce(true)
//                        .requestPermissions(needPermissions )
//                        .requestCodes(needPermissionsNumber)
//                        .requestListener(new Wrapper.PermissionRequestListener() {
//                            @Override
//                            public void permissionGranted(int code) {
//                                switch (code) {
////                                    case ACCESS_COARSE_LOCATION:
////                                        ToastUtil.showShort(mActivity, "地理位置权限授权成功 in fragment with annotation");
////                                        break;
////                                    case ACCESS_FINE_LOCATION:
////                                        ToastUtil.showShort(mActivity, "传感器权限授权成功 in fragment with annotation");
////
////                                        break;
////                                    case WRITE_EXTERNAL_STORAGE:
////                                        ToastUtil.showShort(mActivity, "读取日历权限授权成功 in fragment with annotation");
////                                        break;
////                                    default:
////                                        break;
//                                }
//                            }
//
//                            @Override
//                            public void permissionDenied(int code) {
//                                switch (code) {
////                                    case LOCATION_CODE:
////                                        ToastUtil.showShort(mActivity, "地理位置权限授权失败 in fragment with annotation");
////                                        break;
////                                    case ACCESS_COARSE_LOCATION:
////                                        ToastUtil.showShort(mActivity, "传感器权限授权失败 in fragment with annotation");
////                                        break;
////                                    case CALENDAR_CODE:
////                                        ToastUtil.showShort(mActivity, "读取日历权限授权失败 in fragment with annotation");
////                                        break;
////                                    default:
////                                        break;
//                                }
//                            }
//
//                            @Override
//                            public void permissionRationale(int code) {
//                                switch (code) {
////                                    case LOCATION_CODE:
////                                        ToastUtil.showShort(mActivity, "请开启地理位置权限 in fragment with annotation");
////                                        break;
////                                    case ACCESS_COARSE_LOCATION:
////                                        ToastUtil.showShort(mActivity, "请开启传感器权限 in fragment with annotation");
////                                        break;
////                                    case CALENDAR_CODE:
////                                        ToastUtil.showShort(mActivity, "请开启读取日历权限 in fragment with annotation");
////                                        break;
////                                    default:
////                                        break;
//                                }
//                            }
//                        })
////                        .requestCustomRationaleListener(new Wrapper.PermissionCustomRationaleListener() {
////                            @Override
////                            public void permissionCustomRationale(int code) {
////                                switch (code) {
////                                    case LOCATION_CODE:
////                                        ToastUtil.showShort(mActivity, "请开启地理位置权限 in fragment with annotation");
////                                        Log.e("TAG", "permissionRationale: 请开启地理位置权限 ");
////
////                                        new AlertDialog.Builder(mActivity)
////                                                .setMessage("地理位置权限权限申请：\n我们需要您开启地理位置权限(in fragment with " +
////                                                        "annotation)")
////                                                .setPositiveButton("确定", new DialogInterface
////                                                        .OnClickListener() {
////                                                    @Override
////                                                    public void onClick(DialogInterface dialog, int which) {
////                                                        Permissions4M.get(Main_Activity.this)
////                                                                .requestOnRationale()
////                                                                .requestPermissions(Manifest.permission
////                                                                        .ACCESS_FINE_LOCATION)
////                                                                .requestCodes(LOCATION_CODE)
////                                                                .request();
////                                                    }
////                                                })
////                                                .show();
////                                        break;
////                                    case ACCESS_COARSE_LOCATION:
////                                        ToastUtil.showShort(mActivity, "请开启传感器权限 in fragment with annotation");
////                                        Log.e("TAG", "permissionRationale: 请开启传感器权限 ");
////
////                                        new AlertDialog.Builder(mActivity)
////                                                .setMessage("传感器权限申请：\n我们需要您开启传感器权限(in fragment with " +
////                                                        "annotation)")
////                                                .setPositiveButton("确定", new DialogInterface
////                                                        .OnClickListener() {
////                                                    @Override
////                                                    public void onClick(DialogInterface dialog, int which) {
////                                                        Permissions4M.get(Main_Activity.this)
////                                                                .requestOnRationale()
////                                                                .requestPermissions(Manifest.permission
////                                                                        .ACCESS_COARSE_LOCATION)
////                                                                .requestCodes(ACCESS_COARSE_LOCATION)
////                                                                .request();
////                                                    }
////                                                })
////                                                .show();
////                                        break;
////                                    case CALENDAR_CODE:
////                                        ToastUtil.showShort(mActivity, "请开启读取日历权限 in fragment with annotation");
////                                        Log.e("TAG", "permissionRationale: 请开启读取日历权限 ");
////
////                                        new AlertDialog.Builder(mActivity)
////                                                .setMessage("日历权限申请：\n我们需要您开启日历权限(in fragment with " +
////                                                        "annotation)")
////                                                .setPositiveButton("确定", new DialogInterface
////                                                        .OnClickListener() {
////                                                    @Override
////                                                    public void onClick(DialogInterface dialog, int which) {
////                                                        Permissions4M.get(Main_Activity.this)
////                                                                .requestOnRationale()
////                                                                .requestPermissions(Manifest.permission
////                                                                        .READ_CALENDAR)
////                                                                .requestCodes(CALENDAR_CODE)
////                                                                .request();
////                                                    }
////                                                })
////                                                .show();
////                                        break;
////                                    default:
////                                        break;
////                                }
////
////                            }
////                        })
//                        .request();
//            }
//        });
//    }

}
